package com.android.vgongyi.activity;

import java.util.ArrayList;
import java.util.Random;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.vgongyi.R;
import com.android.vgongyi.common.AppConstant;
import com.android.vgongyi.common.WeiboAdapter;
import com.android.vgongyi.dao.CommonDAO;
import com.android.vgongyi.entity.CommonEntity;
import com.android.vgongyi.service.VGongyiService;
import com.android.vgongyi.utils.SystemUtil;
import com.android.vgongyi.view.PullListView;
import com.android.vgongyi.view.PullListView.OnRefreshListener;
import com.android.vgongyi.view.PullListView.PushRefreshListener;
import com.android.vgongyi.view.VersionDialog;
import com.mobclick.android.MobclickAgent;

public class HomeActivity extends BaseActivity {
	private Button       refreshBtn;
	private PullListView homeListView;
	private WeiboAdapter adapter;
	private ProgressBar  title_progress;
	
	private boolean isRefreshing;
	private boolean isLoading;	
	private ArrayList<CommonEntity> commonList;
	private ArrayList<CommonEntity> adList;
	

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        setCommonTitle(this, R.string.vgongyi);
        
        Intent intent     = getIntent();
        String versionUrl = intent.getStringExtra("versionUrl");
        String versionTip = intent.getStringExtra("versionTip");
        if(!TextUtils.isEmpty(versionUrl)){    			
        	VersionDialog dialog     = new VersionDialog(this,versionUrl,versionTip);
            dialog.show();
        }
        
       new AdData().execute();
        
       CommonDAO commonDAO   = new CommonDAO(getApplicationContext());
       
       homeListView          = (PullListView) this.findViewById(R.id.homelist);
       title_progress        = (ProgressBar) findViewById(R.id.title_progress);
       refreshBtn            = (Button) this.findViewById(R.id.Common_refresh);
       commonList            = commonDAO.query(null, null, null,null);
       
       if(commonList.size() < AppConstant.NO_1){
    	   Toast.makeText(this, "网络不可用,无更新数据!", Toast.LENGTH_LONG).show();
       }
        
       findViewById(R.id.Common_back).setVisibility(View.GONE);
        
        refreshBtn.setVisibility(View.VISIBLE);    	
    	refreshBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				
				if(!isRefreshing){
					
					homeListView.setSelection(0);
					homeListView.clickToRefresh();
		            RefreshData refresh = new RefreshData(HomeActivity.this);
		            refresh.execute();
		            
				}
			}});
    	    	
    	homeListView.setonRefreshListener(new OnRefreshListener() {  
          
    		public void onRefresh() {
            	
            	if(!isRefreshing){
            		
            	  RefreshData refresh = new RefreshData(HomeActivity.this);
  	              refresh.execute();
  	              
            	}
            }  
        });  
    	
    	
    	homeListView.setPushRefreshListener(new PushRefreshListener(){

			@Override
			public void onRefresh() {
	               
				if(!isLoading){
					
					AppendData append = new AppendData();
					append.execute(commonList.get(commonList.size()-1).getId());
					
				}
																						
			}});
    	
    	
    	homeListView.setOnItemClickListener( new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
			
				if(isLoading) return;

			}
		});
    	
    	
    	initData();
    
    }
    
    public void initData(){
    	
    	CommonDAO commonDAO   = new CommonDAO(getApplicationContext());
    	if(commonList!=null) {
    		commonList.clear();
    		commonList = null;
    	}
    	commonList            = commonDAO.query(null, null, null,null);
    	adapter = null;
    	adapter = new WeiboAdapter(commonList,this);
    	homeListView.setAdapter(adapter);
    	
    	insertAdData();
    	
    	TextView msgText = (TextView)findViewById(R.id.msg_count);
    	msgText.setText(R.string.default_msg_count);
    	msgText.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onResume() {
    	
    	super.onResume();
    	MobclickAgent.onResume(this);
    	super.MenuDirectionConfig(this);
    	
    }
    
    public void onPause() {
    	
    	super.onPause();
    	MobclickAgent.onPause(this);
    	
    }
    
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("onActivityResult");
		if (resultCode != RESULT_OK)
            return;
		switch (requestCode) {
			case 1:
		    	commonList.clear();
		    	AppendData append = new AppendData();
		    	System.out.println("passid------>"+data.getStringExtra("data"));
				append.execute(data.getStringExtra("data"));
				break;
			default:
				break;
		}
	}

	private void insertAdData(){
    	if(adList == null||adList.size() == 0){
    		return;
    	}
    	cleanAdData();
    	int position = 0;
    	for (int i = 0; i < adList.size(); i++) {
    		position = position+ 1 + new Random().nextInt(9);
			adList.get(i).setWeibo_id(AppConstant.TAG_AD);
			if(commonList.size() < position){
				break;
			}
			commonList.add(position, adList.get(i));
		}
    }
    
    private void cleanAdData(){
    	for(int i =0;i < commonList.size();i++){
    		if(commonList.get(i).getWeibo_id().equals(AppConstant.TAG_AD)){
    			commonList.remove(i);
    		}
    	}
    }
    
    class RefreshData extends AsyncTask<String, String, Integer>{

    	RefreshData(Context context){
    		
    		if(!SystemUtil.checkNetwork(context))  Toast.makeText(context, R.string.network_unavailable, Toast.LENGTH_SHORT).show();
    		
    		title_progress.setVisibility(View.VISIBLE);
        	refreshBtn.setVisibility(View.GONE);
        	
    	}
    	
		@Override
		protected Integer doInBackground(String... params) {
			
			isRefreshing                 = true;
			int result                   = 0;
			VGongyiService service       = new VGongyiService(HomeActivity.this);
			ArrayList<CommonEntity> list = service.getLatestCommonFeeds();
			if(list == null)  return 0;
			result              = list.size();
			CommonDAO commonDAO = new CommonDAO(getApplicationContext());
			
			for(int i = 0;i < list.size();i++){
				
				 if(commonDAO.query(null, "id = '"+list.get(i).getId()+"'", null, null).size() > 0)    result -- ;
				 
			 }
			
			if(list.size()>0){
				commonDAO.delete(null, null);
				for(CommonEntity entity:list)
					commonDAO.insert(entity);
			}
			
			commonList.clear();
            commonList.addAll(commonDAO.query(null, null, null,null));
            insertAdData();
			
			return result;		
		}

		@Override
		protected void onPostExecute(Integer result) {
			
			TextView msg_count           = (TextView) findViewById(R.id.msg_count);
			final TextView  update_count = (TextView) findViewById(R.id.update_count);
			
			if(result == 0){
				
				msg_count.setVisibility(View.INVISIBLE);
				update_count.setVisibility(View.VISIBLE);
				update_count.setText(R.string.no_new_message);
				
			}else{
				
				msg_count.setVisibility(View.VISIBLE);
				update_count.setVisibility(View.VISIBLE);
				msg_count.setText(String.valueOf(result));
				update_count.setText(String.format(getResources().getString(R.string.message_sum), String.valueOf(result)));
				
			}
			
			final Handler handler = new Handler(){
				@Override
				public void handleMessage(Message msg) {
					
		                switch (msg.what) {
		                
		                    case 1:
		                    	
		                    	update_count.setVisibility(View.GONE);
		                        break;
		                }
		          }
			};
			
			new Thread(new Runnable() {
				
		            public void run() {
		            	
		                Message message = new Message();
						message.what = 1;
		                handler.sendMessage(message);
		                
		            }
		        }).start();
			
        	adapter.notifyDataSetChanged(); 
        	homeListView.onRefreshComplete();
        	title_progress.setVisibility(View.GONE);
        	refreshBtn.setVisibility(View.VISIBLE);
        	isRefreshing = false;
			super.onPostExecute(result);
		}
    }
    
    class AppendData extends AsyncTask<String, String, String>{
    	
    	AppendData(){
    		
    		isLoading     = true;
    	}
    	
		@Override
		protected String doInBackground(String... params) {
			
			 try {    
				 
				 
             	 String from_id                  = params[0];                        	
                 VGongyiService service          = new VGongyiService(HomeActivity.this);
                 ArrayList<CommonEntity> newList = service.getCommonFeeds(from_id);
                 commonList.addAll(newList); 
                 insertAdData();
                 
             } catch (Exception e) {}
			 
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			
			isLoading = false;
			adapter.notifyDataSetChanged();
			homeListView.pushRefreshComplete();
			super.onPostExecute(result);
		}
	}
    
    class AdData extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			VGongyiService service       = new VGongyiService(HomeActivity.this);
			adList = service.getAdList();
			return null;
			
		}
    	
    }
    
}